<template>
	<div class="main">
		<div class="main-header" v-if="buttons.length" style="display: flex; justify-content: space-between">
			<div style="display: flex">
				<el-input placeholder="请输入内容" style="width: 200px; margin-right: 10px" v-model="searchParamCp.keyword" size="mini" clearable> </el-input>
				<el-select v-model="searchParamCp.cate_id" size="mini" placeholder="请选择商品分类" style="width: 200px; margin-right: 10px">
					<el-option v-for="item in catelist" :key="item.id" :label="item.name" :value="item.id"> </el-option>
				</el-select>
				<el-button type="primary" size="mini" @click="searchs()">搜索</el-button>
				<el-button size="mini" @click="reset()">重置</el-button>
			</div>
			<div style="display: flex">
				<elUploadFile style="margin-right: 10px" :title="'导入'" :auto-upload="false" :upload-clear="true" :show-file-list="false" @change="upload" :limit="1" :multiple="false" accept=".xls,.xlsx" class="ml-10">
					<el-button type="primary">导入</el-button>
				</elUploadFile>
				<!-- <el-button size="mini" @click="upload()">导入</el-button> -->
				<el-button size="mini" v-for="(item, index) in buttons" :key="index" :type="item.path | formatType" :icon="item.icon" :disabled="item.path | formatDisabled(selection)" @click="tapButton(item)">{{ item.title }}</el-button>
			</div>
		</div>
		<el-table ref="table" class="main-table" :data="goodsData" height="100%" border header-cell-class-name="main-table-header" @selection-change="onSelectionChange" @row-click="onRowClick">
			<el-table-column type="selection" width="39"> </el-table-column>
			<el-table-column label="商品图片">
				<template slot-scope="{ row }">
					<el-image style="width: 60px; height: 60px" :src="row.url" :preview-src-list="[row.url]"> </el-image>
				</template>
			</el-table-column>
			<el-table-column align="center" label="商品名称" prop="goods_name" />
			<el-table-column align="center" label="商品分类" prop="cate_name" />
			<el-table-column align="center" label="商品金额" prop="goods_price_min" />
			<el-table-column lign="center" label="商品库存" prop="stock_total">
				<template slot-scope="{ row }">
					<div>{{ row.stock_total == 0 ? "已售罄" : row.stock_total }}</div>
				</template>
			</el-table-column>
			<el-table-column align="center" label="进货价" prop="line_price_max" />
			<el-table-column align="center" label="启用状态" prop="status">
				<!-- status状态  10上架 20下架 -->
				<template slot-scope="{ row }">
					<el-switch v-model="row.status == 20 ? false : true" disabled> </el-switch>
					<!-- <el-switch v-model="row.status" active-value="10" inactive-value="20"></el-switch> -->
				</template>
			</el-table-column>
			<el-table-column label="上架时间" width="150">
				<template slot-scope="{row}">
					{{ row.create_time | formatDate }}
				</template>
			</el-table-column>
			<el-table-column align="center" label="操作" prop="status">
				<template slot-scope="{ row }">
					<el-button type="primary" @click="onEdit(row)">编辑</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination class="main-pagination" :current-page.sync="page" :page-size="limit" :total="total" @current-change="onCurrentChange" layout="total,jumper,prev,pager,next"></el-pagination>
		<el-dialog :visible.sync="dialogVisible" :title="dialogTitle" append-to-body width="800px" @close="onDialogClose">
			<component :is="dialogView" @update="getGoodsData" :selection="selection"></component>
		</el-dialog>
	</div>
</template>

<script>
import { get, del, imghttp, post } from "@/assets/js/http.js"
import Search from "./search.vue"
import Add from "./add.vue"
import elUploadFile from "@/components/el-upload-file.vue"
// import Edit from "./edit.vue";

export default {
	name: "view-goods",
	data() {
		return {
			goodsData: [],
			selection: [],
			page: 1,
			limit: 20,
			total: 0,
			dialogVisible: false,
			dialogTitle: "",
			dialogView: "",
			searchParamCp: {},
			catelist: [],
			searchinfo: {
				keyword: "",
				cate_id: "",
			},
		}
	},
	computed: {
		buttons() {
			return this.$store.state.buttons
		},
	},
	components: {
		Add,
		Edit: () => import("./edit.vue"),
		Search,
		elUploadFile,
	},
	mounted() {
		this.getGoodsData()
		this.getcate()
	},
	// onShow(){
	// 	this.getGoodsData();
	// },
	beforeRouteEnter(to, from, next) {
		next((vm) => {
			console.log(from.path, "vm from")
			if (from.path != "/goods/edit" && vm) {
				console.log(vm.$store.state, "vmm")
				vm.$store.dispatch("setKeepAlive", [])
			} else {
				vm.getGoodsData()
			}
		})
	},
	methods: {
		getcate() {
			get({
				url: "/admin/shop.GoodsCategory/index",
				params: {
					limit: 999,
				},
			}).then((res) => {
				this.catelist = res.list
				console.log(res)
			})
		},
		async getGoodsData() {
			const data = await get({
				url: "/admin/shop.goods/index",
				loading: true,
				params: {
					limit: this.limit,
					page: this.page,
					...this.searchinfo,
				},
			})
			this.goodsData = data.list
			this.total = data.total
		},
		//重置
		reset() {
			this.searchParamCp = {}
			;(this.searchinfo = {
				keyword: "",
				cate_id: "",
			}),
				this.getGoodsData()
		},
		//搜索
		searchs() {
			this.page = 1
			this.searchinfo = {
				...this.searchinfo,
				...this.searchParamCp,
			}
			this.getGoodsData()
		},
		onCurrentChange(index) {
			this.page = index
			this.getGoodsData()
		},
		onAdd() {
			this.$router.push("/goods/add")
		},
		onEdit(row) {
			this.$store.dispatch("setKeepAlive", ["view-goods"])
			this.$nextTick(() => {
				this.$router.push({
					path: "/goods/edit",
					query: {
						id: row.id,
					},
				})
			})
			// this.$router.push("/goods/edit")
			// this.dialogTitle = "编辑商品";
			// this.dialogView = "Edit";
			// this.dialogVisible = true;
		},
		onSearch() {
			this.dialogTitle = "搜索商品"
			this.dialogView = "Search"
			this.dialogVisible = true
		},
		onDelete() {
			this.$confirm(`此操作将永久删除该${this.selection.length}个商品, 是否继续?`, "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(async () => {
					let query = "?"
					for (let i = 0; i < this.selection.length; i++) {
						const item = this.selection[i]
						if (i > 0) {
							query += "&ids[]=" + item.id
						} else {
							query += "ids[]=" + item.id
						}
					}
					await del({
						url: "/admin/shop.goods/del" + query,
						successTip: true,
						loading: true,
					})
					this.getGoodsData()
				})
				.catch(() => {
					this.$refs.table.clearSelection()
				})
		},
		onSelectionChange(selection) {
			this.selection = selection
		},
		onRowClick(row) {
			this.$refs.table.toggleRowSelection(row)
		},
		onDialogClose() {
			this.$refs.table.clearSelection()
		},
		tapButton(item) {
			if (item.path === "add") {
				this.onAdd()
			} else if (item.path === "edit") {
				this.onEdit()
			} else if (item.path === "delete") {
				this.onDelete()
			} else if (item.path === "search") {
				this.onSearch()
			} else if (item.path === "daoru") {
				this.upload()
			} else if (item.path === "download") {
				this.exportExcel()
			} else if (item.path === "export") {
				this.export()
			}
		},
		//导出模板
		async exportExcel() {
			this.$loading()
			let res = await post({
				export: true,
				url: "/admin/shop.Goods/import_url",
				// params: {
				// 	...this.searchinfo,
				// 	...{
				// 		search_time: this.searchinfo.search_time && this.searchinfo.search_time
				// 			.length ? this.searchinfo.search_time.join(' - ') : ''
				// 	}
				// }
			})
			console.log(res)
			window.open(res.url)
			// let a = document.createElement('a');
			// var url = URL.createObjectURL(res);
			// a.href = url;
			// a.click();
			this.$loading().close()
		},
		//导出
		async export() {
			this.$loading()
			let res = await get({
				export: true,
				url: "/api/Realmerit/goods_export",
				params: {
					...this.searchinfo,
					...{
						search_time: this.searchinfo.search_time && this.searchinfo.search_time.length ? this.searchinfo.search_time.join(" - ") : "",
					},
				},
			})
			let a = document.createElement("a")
			var url = URL.createObjectURL(res)
			a.href = url
			a.click()
			this.$loading().close()
		},
		//导入
		async upload({ raw }) {
			console.log(raw, "raw")
			this.$loading({
				text: "导入中 请等待...",
			})
			await imghttp({
				url: "/admin/shop.Goods/import",
				data: {
					file: raw,
				},
				successTip: true,
			})
			this.getGoodsData()
			this.$loading().close()
		},
	},
}
</script>
